﻿﻿define(function(require,exports,module){
	require("resource/js/easyui/easyloader.js");
	var canvas_ = require("resource/js/component/canvas.js");
	var ajax = require("resource/js/component/ajax.js");
	var sectionId = sessionStorage.getItem('sectionId');
	var metre = 3; /** 3m = 60px */
    var pixel = metre / 60; /** 1px=3 / 60 = 0.05m */
    var TrackLength = 2;  /** 轨迹长度2m */
    var gridPixel = TrackLength / pixel; /** 轨迹长度所占的像素 */
    var gridSize = 2;  /** 网格大小为2px */
    var gridNumber = gridPixel / gridSize; /** 网格数量 */
    var a = 6378137;  /** 长半径a=6378137 */
    var b = 6356752.3142;  /** 短半径b=6356752.3142 */
    var f = 1 / 298.2572236; /** 扁率f=1/298.2572236 */
    var cornersLngLat=[];
    var obtainGridList=[];  /** 路桩所有xy坐标 */
    var obtainGridLatLng =[];  /** 路桩所有经纬度 */
    var lngLatGridList=[];  /** 轨迹所有xy坐标 */
    var locusgridLngLat =[]; /** 轨迹所有经纬度坐标 */
    var vehicleAllList = []; //车辆列表
    var vehicleTypeData = [];
    var dataJson = {};
    var tanpucarJosn = {}; //摊铺机压过的所有网格
    var scrollFlag = false;
    var darwCenterPointLngLat = {};  /** 屏幕中心点经纬度 */
    var drawPathArr = [];
	var drawWidth = $("body").width(); 
	var drawHeight = $("body").height();
	scaleX =undefined;
	scaleY =undefined;
	var vehicleIdSimplify = {};// 车辆id简化
	var xOffset = 0;
	var yOffset = 0;
	var pageWidth = 0; 
	var pageHeight = 0;
	var endData = [];
	var statisticalTimes = {};
	var xscreenflag = true;
	var yscreenflag = true;
	var isReport = $("#isReport").val();
	var isReportFlag = true;
	
	 /**
     * 根据中心点经纬度计算四角经纬度的公式
     *
     */
	
    function computerThatLonLat(lon, lat, brng, dist) {
        var alpha1 = rad(brng);
        var sinAlpha1 = Math.sin(alpha1);
        var cosAlpha1 = Math.cos(alpha1);
        var tanU1 = (1 - f) * Math.tan(rad(lat));
        var cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1));
        var sinU1 = tanU1 * cosU1;
        var sigma1 = Math.atan2(tanU1, cosAlpha1);
        var sinAlpha = cosU1 * sinAlpha1;
        var cosSqAlpha = 1 - sinAlpha * sinAlpha;
        var uSq = cosSqAlpha * (a * a - b * b) / (b * b);
        var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

        var cos2SigmaM=0;
        var sinSigma=0;
        var cosSigma=0;
        var sigma = dist / (b * A), sigmaP = 2 * Math.PI;
        while (Math.abs(sigma - sigmaP) > 1e-12) {
            cos2SigmaM = Math.cos(2 * sigma1 + sigma);
            sinSigma = Math.sin(sigma);
            cosSigma = Math.cos(sigma);
            var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
                    - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
            sigmaP = sigma;
            sigma = dist / (b * A) + deltaSigma;
        }

        var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
        var lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
                (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
        var lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
        var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
        var L = lambda - (1 - C) * f * sinAlpha
                * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

        var revAz = Math.atan2(sinAlpha, -tmp); // final bearing
        cornersLngLat.push({
        	lng:Number(Number(lon)+Number(deg(L))),
        	lat:deg(lat2)
        });
    }
	
    /**
     * 度换成弧度
     *
     * @param d
     *            度
     * @return 弧度
     */
    function rad(d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 弧度换成度
     *
     * @param x
     *            弧度
     * @return 度
     */
    function deg(x) {
        return x * 180 / Math.PI;
    }
	
    /**
     * 绘制背景网格
     *
     */
    
	function initPage(){
		var w=$("#canvas_").width();
		var h=$("#canvas_").height();
		var tmp = 100;
		var i = h/tmp;
		for(j=0;j<i;j++){
			canvas.beginPath().lineWidth(1).strokeStyle("#ccc").moveTo(0,j*tmp).lineTo(w,j*tmp).stroke();
		}
		i = w/tmp;
		for(j=0;j<i;j++){
			canvas.beginPath().lineWidth(1).strokeStyle("#ccc").moveTo(j*tmp,0).lineTo(j*tmp,h).stroke();
		}
	}

	 /**
     * 画布拖拽处理
     *
     */
	
	var newgrad = function(xSesult,ySesult){
		var canvas_svghtml = $("#canvas_svg");
		var canvas_html = $("#canvas_");
		var top = null, left=null;
		//给拖拽的坐标赋值
		top = canvas_svghtml.attr("top");
		left = canvas_svghtml.attr("left");
		if(top<0 &&ySesult>0 ||top<0 &&ySesult<0){
			top = Number(top)+Number(ySesult);
		}
		if(top==0){
			top = ySesult;
		}
		if(left<0 &&xSesult>0 ||left<0 &&xSesult<0){
			left = Number(left)+Number(xSesult);
		}
		if(left==0){
			left = xSesult;
		}
		if(top>0) top =0;
		if(left>0) left = 0;
		if(Math.abs(top)+$("body").height()>canvas_html.height()){
			top = -(canvas_html.height()-$("body").height());
		}
		if(Math.abs(left)+$("body").width()>canvas_html.width()){
			left = -(canvas_html.width()-$("body").width());
		}
		var enddragX = left - canvas_html.attr("left");//画布最终拖动了多少
		var enddragY = top - canvas_html.attr("top");
		canvas_html.attr("top",top);
		canvas_html.attr("left",left);
		canvas_html.css({
			top:top,
			left:left
		});
		canvas_svghtml.attr("top",top);
		canvas_svghtml.attr("left",left);
		canvas_svghtml.css({
			top:top,
			left:left
		});
		
		var canvasCar = $(".tanpucar");
		canvasCar.each(function(){
			var carTop = $(this).attr("top");
			var carLeft = $(this).attr("left");
			carTop = Number(enddragY)+Number(carTop);
			carLeft = Number(enddragX)+Number(carLeft);
			$(this).css({
				left:carLeft,
				top:carTop,
			});
			$(this).attr("left",carLeft);
			$(this).attr("top",carTop);
			
		});
	};
	
	 /**
     * 拖动函数
     *
     */
	
	function Mover(title) {
        this.obj = title;
        this.startx = 0;
        this.starty;
        this.startLeft;
        this.startTop;
        this.mainDiv = title.parentNode;
        var that = this;
        this.isDown = false;
        this.movedown = function (e) {
            e = e ? e : window.event;
            if (!window.captureEvents) {
                this.setCapture();
            }  
//            事件捕获仅支持ie
//            函数功能：该函数在属于当前线程的指定窗口里设置鼠标捕获。一旦窗口捕获了鼠标，
//            所有鼠标输入都针对该窗口，无论光标是否在窗口的边界内。同一时刻只能有一个窗口捕获鼠标。
//            如果鼠标光标在另一个线程创建的窗口上，只有当鼠标键按下时系统才将鼠标输入指向指定的窗口。
//            非ie浏览器 需要在document上设置事件
            that.isDown = true;
            that.startx = e.clientX;
            that.starty = e.clientY;
            that.startLeft = parseInt(that.mainDiv.style.left);
            that.startTop = parseInt(that.mainDiv.style.top);
        }
        this.move = function (e) {
            e = e ? e : window.event;
            if (that.isDown) {
                that.mainDiv.style.left = e.clientX - (that.startx - that.startLeft) + "px";
                that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px";
            }
        }
        this.moveup = function (e) {
            that.isDown = false;
            if (!window.captureEvents) {
                this.releaseCapture();
            } 
            //事件捕获仅支持ie
            var xSesult = e.clientX - that.startx;
            var ySesult = e.clientY - that.starty;
            newgrad(xSesult,ySesult);
        }
        this.obj.onmousedown = this.movedown;
        this.obj.onmousemove = this.move;
        this.obj.onmouseup = this.moveup;

        //非ie浏览器
        document.addEventListener("mousemove", this.move, true);
    }
	
	 /**
     * 绘制路辅
     *
     */
	
	var getVectorModule=function(vector){
		return Math.sqrt(vector.x*vector.x+vector.y*vector.y);
	}
	
	var getUtilVector=function(vector){
		var vModule=getVectorModule(vector);
		if(0==vModule){
			return null;
		}
		return {x:vector.x/vModule,y:vector.y/vModule};
	}
	
	var getPinleftOfV=function(p,p1,p2){
		return (p.x-p1.x)*(p2.y-p1.y)-(p.y-p1.y)*(p2.x-p1.x);
	}
	
	var getNormal=function(position,vector,length){
		var result=[{x:0,y:0},{x:0,y:0}];
		if(vector.x==0){
			result[0].x=position.x-length;
			result[0].y=position.y;
			result[1].x=position.x+length;
			result[1].y=position.y;
			return result;
		}
		var xSlope = vector.y / vector.x;
		
		if( xSlope != 0){
			var ySlope = -(1 / xSlope);
			result[0].x = Math.ceil(-1 /  Math.sqrt(1 + ySlope * ySlope)*length + position.x);
			result[1].x = Math.ceil(1 /  Math.sqrt(1 + ySlope * ySlope)*length + position.x);
			result[0].y = Math.ceil(-ySlope /  Math.sqrt(1 + ySlope * ySlope)*length + position.y);
			result[1].y = Math.ceil(ySlope /  Math.sqrt(1 + ySlope * ySlope)*length + position.y);
		}
		
		if(xSlope == 0){
			result[0].x  = position.x;
			result[0].x = position.x;
			result[1].y  = position.y - length;
			result[1].y = position.y + length
		}
		
		return result;
	}
	
	var roadPath = function(option){
		var topArr = [];
		var bottomArr = [];
		var result=[{x:0,y:0},{x:0,y:0}];;
		if(option.length<2){
			return;
		}
		for(var i=0; i<option.length;i++){
			var roadWidth = (option[i].roadWidth * (60 / metre)) / 2;
			if(0==i){
				var v={x:option[1].x-option[0].x,y:option[1].y-option[0].y };
				result=getNormal(option[0],v,roadWidth);
				var temp = getPinleftOfV(result[0],option[0],option[1]);
				if(temp < 0){
					var tempv=result[1];
					result[1]=result[0];
					result[0]=tempv;
				}
			}else if(i==option.length-1){
				
				var v={x:option[option.length-2].x-option[option.length-1].x,y:option[option.length-2].y-option[option.length-1].y };
				result=getNormal(option[option.length-1],v,roadWidth);
				var temp = getPinleftOfV(result[0],option[option.length-2],option[option.length-1]);
				if(temp < 0){
					var tempv=result[1];
					result[1]=result[0];
					result[0]=tempv;
				}
			}else{
				var a={x:option[i-1].x-option[i].x,y:option[i-1].y-option[i].y };
				var b={x:option[i+1].x-option[i].x,y:option[i+1].y-option[i].y };
				var ua=getUtilVector(a),ub=getUtilVector(b);
//				console.log(ua.x*ua.x+ua.y*ua.y);
//				console.log(ub.x*ub.x+ub.y*ub.y);
				var tempUtilv=getUtilVector({x:(ua.x+ub.x),y:(ua.y+ub.y)});
				if(null ==tempUtilv){
					continue;
				}
				result[0].x=option[i].x+tempUtilv.x*roadWidth;
				result[0].y=option[i].y+tempUtilv.y*roadWidth;
				result[1].x=option[i].x-tempUtilv.x*roadWidth;
				result[1].y=option[i].y-tempUtilv.y*roadWidth;
				
				var temp = getPinleftOfV(result[0],option[i],option[i+1]);
				if(temp < 0){
					var tempv=result[1];
					result[1]=result[0];
					result[0]=tempv;
				}
			}
			topArr.push(Math.ceil(result[0].x) , Math.ceil(result[0].y));
			bottomArr.unshift(Math.ceil(result[1].x) , Math.ceil(result[1].y));
		}
		var roadSvg = topArr.concat(bottomArr);
		canvas.lineWidth(1).strokeStyle("rgba(0, 0, 0, 0.2)").fillStyle("rgba(0, 0, 0, 0.2)").polygon(roadSvg);
	}
	
	/**
     * 绘制路桩，路辅
     *
     */
	
	var roadAssist = function(option){
		for(var i=1; i<option.length;i++){
			canvasvg.beginPath().lineWidth(8).strokeStyle("#ffe500").moveTo(option[i-1].x,option[i-1].y).lineTo(option[i].x,option[i].y).stroke();
    	}
		
		if(metre<300){
			for(var i=0; i<option.length;i++){
				var $option = option[i];
				canvasvg.beginPath().strokeStyle("lightblue").arc($option.x,$option.y).stroke();
				canvasvg.font("bold 25px Georgia").fillStyle("#ffe500").fillText($option.pileKey,$option.x,$option.y);
			}
		}
	}
	
	/**
     * 初始化确定画布偏移位置
     *
     */
	
	var setLocation = function(){
		var setCanvas = $("#canvas_");
		var setcanvas_svg = $("#canvas_svg");
		var bodylist = $("body");
		var leftOffset = null;
		var topOffset  = null;
		if(xOffset!=0){
			leftOffset = Math.abs(xOffset)+roadWidth;
		}else{
			leftOffset = roadWidth;
		}
		if(yOffset!=0){
			topOffset =  Math.abs(yOffset)+roadWidth;
		}else{
			topOffset = roadWidth;
		}
		setCanvas.attr("top",-topOffset);
		setCanvas.attr("left",-leftOffset);
		setCanvas.css({top:-roadWidth,left:-leftOffset});
		setcanvas_svg.attr("top",-topOffset);
		setcanvas_svg.attr("left",-leftOffset);
		setcanvas_svg.css({top:-topOffset,left:-leftOffset});
	}
	
	 /**
     * 绘制路桩，路桩点
     *
     */
	
    var darwObtainLine = function(option){
    	roadWidth = (option[0].roadWidth * (60 / metre)) / 2;
		for(var k=0;k<option.length;k++){
			if(xOffset!=0){
				option[k].x = option[k].x + Math.abs(xOffset) + roadWidth;
			}else{
				option[k].x = option[k].x + roadWidth;
			}
			
			if(yOffset!=0){
				option[k].y = option[k].y + Math.abs(yOffset) + roadWidth;
			}else{
				option[k].y = option[k].y + roadWidth;
			}
		}
		
    	var bodyHeight = $("body").height();
    	var bodyWidth = $("body").width();
    	if(Math.abs(xOffset) > pageWidth){
    		xWidth = Math.abs(xOffset) + bodyWidth + roadWidth;
    	}else{
    		xWidth = pageWidth + bodyWidth + roadWidth;
    	}
    	if(Math.abs(yOffset) > pageHeight){
    		yHeight = Math.abs(yOffset) + bodyHeight + roadWidth;
    	}else{
    		yHeight = pageHeight + bodyHeight + roadWidth;
    	} 
        $('<canvas id="canvas_" width="'+xWidth+'" height="'+yHeight+'"></canvas><canvas id="canvas_svg" width="'+xWidth+'" height="'+yHeight+'"></canvas>').appendTo($(".canvasbody"));
		canvas = canvas_.init(document.getElementById("canvas_").getContext("2d"));
		canvasvg = canvas_.init(document.getElementById("canvas_svg").getContext("2d"));
		initPage();
		roadPath(option);
		setLocation();
		roadAssist(option);
		vehicleList();
		$canvas_top = $("#canvas_svg").attr("top");
		$canvas_left = $("#canvas_svg").attr("left");
    	var mover = new Mover(document.getElementById("canvas_svg"));
    	document.getElementById("canvas_svg").onmousemove = function(e){
    		var lng = Number((e.x*scaleX/3600)) + Number(cornersLngLat[0].lng);
    		var lat = Number(cornersLngLat[0].lat)-Number((e.y*scaleY/3600));
    		$("#getlnglat").text(lng +"  "+ lat +" " + e.x +" " + e.y);
		}
    };
	
    /**
     * 所有经纬度转换为页面xy坐标
     *
     */
    
    var getCoordinate = function(data,Roadpile,id){
    	if(!scaleX)
    		scaleX = Math.abs(((cornersLngLat[1].lng - cornersLngLat[0].lng)*3600) / drawWidth);
    	if(!scaleY)
    		scaleY = Math.abs(((cornersLngLat[0].lat - cornersLngLat[3].lat)*3600) / drawHeight);
    	var screenX  = (data.lng-cornersLngLat[0].lng)*3600/scaleX;
    	var screenY  = (Number(cornersLngLat[0].lat)-Number(data.lat))*3600/scaleY;
    	screenX = Math.ceil(screenX);
		screenY = Math.ceil(screenY);
		if(screenX % 2 != 0){
			screenX = screenX + 1;
		}
		if(screenY % 2 != 0){
			screenY = screenY + 1;
		}
    	if(Roadpile==1){
    		if(screenX < 0 && xscreenflag){
    			xscreenflag = false;
    			xOffset = screenX;
    		}else if(screenX < 0 && screenX < xOffset){
    			xOffset = screenX;
    		}
    		if(screenY < 0 && yscreenflag){
    			yscreenflag = false;
    			yOffset = screenY;
    		}else if(screenY < 0 && screenY < yOffset){
    			yOffset = screenY;
    		}
    		
    		if(screenX > 0 && screenX > pageWidth){
    			pageWidth = screenX;
    		}
    		if(screenY > 0 && screenY > pageHeight){
    			pageHeight = screenY;
    		}
    		
    		obtainGridList.push({
    			x:screenX,
    			y:screenY,
    			pileKey:data.pileKey,
    			roadWidth:data.roadWidth
    		});
    	}else{
    		if(!lngLatGridList[id]){
    			lngLatGridList[id]=[];
    		}
    		lngLatGridList[id].push({
    			x:screenX,
    			y:screenY,
    			conId:id,
    			runSpeed:data.runSpeed, //速度
				temperature:data.temperature, //温度
				time:data.time
    		});
    	}
    }
    
    /**
     *  路桩经纬度转换x,y坐标
     * 
     */
    
    var obtainGrid = function(data){
    	for(var k=0; k<data.length;k++){
    		getCoordinate(data[k],1);
    	}
        darwObtainLine(obtainGridList);
    };
    
    /**
     * 查询所有路桩的经纬度
     *
     */
    
    var getRoadPile = function(){
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			obtainGridLatLng = data;
    			obtainGrid(data);
    		}
    		dynamictrack();
    	}).post(BASEPATH + '/dcs/intface/queryPileKey.htm', {sectionId:sectionId});
    }
    
    /**
     * 根据中心点计算四个边角经纬度
     *
     */
    
    var lngLatCount = function(data){
	    var wHalf = drawWidth/2;
	    var hHalf = drawHeight/2;
	    /** 两点之间的距离 */
	    var dist =  Math.sqrt(wHalf * wHalf + hHalf * hHalf)*pixel; 
	    /** 两点之间的夹角 */
	    var brng = Math.atan(wHalf/hHalf)* (180/Math.PI);
	    var angle = [360-brng,brng,180-brng,180+brng]
	    for(var i=0;i<angle.length;i++){
	        computerThatLonLat(data.lng, data.lat, angle[i], dist);
	    }
	    if(obtainGridLatLng.length==0){
	    	getRoadPile();
	    }else{
	    	obtainGrid(obtainGridLatLng);
	    	gridcanvas(locusgridLngLat);
	    }
	    
    }
    
    /**
     *  获取中心点的经纬度
     * 
     */
    
    var getCenterPoint = function(){
    	var option={
    			time:$("#gridTime").val(),
    			sectionId:sectionId
    	};
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			darwCenterPointLngLat = {
    				lat: data.lat,
    				lng: data.lng
        		};
    			lngLatCount(darwCenterPointLngLat);
    		}
    	}).post(BASEPATH + '/dcs/intface/findCenterCoor.htm', option);
    };
    
   
	var trackNumberColor = [
		    "#fff",
			"#c5d3ef",
			"#88aeec",
			"#5894f0",
			"#196df1",
			"#0048c0",
			"#c256fa",
			"#a215eb",
			"#8e15eb",
			"#6e0aca",
			"#6af3a6",
			"#61d996",
			"#44b27e",
			"#069255",
			"#008700",
			"#005d03",
			"#ff5119",
			"#c31405",
			"#611801",
			"#360200",
			"#140100",
		];
	
	var $colorLength = trackNumberColor.length;
	var speendColor = {
			"slow":"#0061ff",
			"normal":"#26ad23",
			"fast":"#d51200"
	}
	
	/**
     *  根据车辆类型，添加车辆图片
     * 
     */
	var tanpuHeight=0;
	var tanpuWidth = 0;
	var carPicType = function(darwID,endList){
		for(var c in vehicleAllList){
			var carDataList = vehicleAllList[c];
			if(carDataList.id ==darwID){
				gridPixel = Math.ceil(carDataList.vehicleWidth /pixel);
				if(gridPixel % 2 !=0){
					gridPixel= gridPixel+1;
				}
				
				var vehicleNameText = "<div class='matchVehicleName'>"+carDataList.vehicleName+"</div>";
				if(carDataList.vehicleType=="01"){//摊铺机
					if(endList.isX){
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/tanpucar.png' />";
					}else{
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/tanpucar11.png' />";
					}
					
				}else if(carDataList.vehicleType=="02"){//胶轮压路机
					if(endList.isX){
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/jiaoluncar.png' />";
					}else{
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/jiaoluncar11.png' />";
					}
					
				}else{//钢轮压路机
					if(endList.isX){
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/carimage.png' />";
					}else{
						var carImgPic = "<img src='"+BASEPATH+"/resource/images/carimage11.png' />";
					}
				}
				$("#car"+darwID).remove();
				$("<div id='car"+darwID+"' class='tanpucar' left="+leftList+" top="+topList+">" +
				vehicleNameText + carImgPic +"</div>").appendTo($(".vehicle"));
				var topList = Number(endList.y) + Number($canvas_top)-gridPixel/2;
				var leftList = Number(endList.x) + Number($canvas_left)-gridPixel/2;
				var carImge = $("#car"+darwID);
				carImge.attr("left",leftList);
				carImge.attr("top",topList);
				carImge.css({top:topList,left:leftList});
				/*if(darwRes=="01"){//摊铺车
					$("#car"+darwID).find(".matchVehicleName").css("top","-45px");
					$("#car"+darwID).find(".matchVehicleName").css("left","18px");
				}*/
				if(endList.isX){
					if(tanpuHeight!=0){
						$("#car"+darwID).find("img").css({
							height:gridPixel,
							width:tanpuHeight
						});
					}else{
						$("#car"+darwID).find("img").css({
							height:gridPixel,
							width:"auto"
						});
					}
					
					tanpuWidth = $("#car"+darwID).find("img").width();
				}else{
					if(tanpuWidth!=0){
						$("#car"+darwID).find("img").css({
							width:gridPixel,
							height:tanpuWidth
						});
					}else{
						$("#car"+darwID).find("img").css({
							width:gridPixel,
							height:"auto"
						});
					}
					tanpuHeight = $("#car"+darwID).find("img").height();
				}
				
				break;
			}
		}
		return gridPixel;
	}
	
	/**
     *  轨迹经纬度转换x,y坐标
     * 
     */
	
	var gridcanvas = function(data){
		$(".errorTip").text("数据处理中");
		var gridID = null;
		for(var k in data.construction){
			for(var m in vehicleIdSimplify){
				if(k == m){
					gridID = vehicleIdSimplify[m];
				} 
			}
			var vhicleData = data.construction[k];
			for(var n=0;n<vhicleData.length;n++){
				getCoordinate(vhicleData[n],0,gridID);
			}
		}
		
		for(var i in lngLatGridList){
			var tmpdata = lngLatGridList[i];
			var firstDAta = tmpdata[0];
			for(var m=1;m<tmpdata.length;m++){
				var tepJosn = tmpdata[m];
				if(firstDAta.x == tepJosn.x && firstDAta.y == tepJosn.y){
//					delete vehicleCoordinateAll[i][m];
					tmpdata.splice(m,1);
					m--;
				}else{
					firstDAta = tmpdata[m];
				}
			}
		}
		
		darwGridLine(lngLatGridList);
	};
	
	/**
     *  数据预处理
     * 
     */
	
	var dataPreprocess = function(data){
//		data.length =1;
		endData = [];
		if(data.length == 0){
			return endData;
		}else{
			if(data.length==1){
				carPicType(data[0].conId,data[0])
			}
			var first = [];
			for(var min=0; min<data.length;min++){
				var Xdifference = 0;
				var Ydifference = 0;
				var $datamin = data[min];
				$datamin.x = Number($datamin.x) - Number($canvas_left);
				$datamin.y = Number($datamin.y) - Number($canvas_top);
				if(min==0){
					first = Object.assign({},data[0]);
				}
				if(min>0){
					first = Object.assign({},data[min-1]);
					Xdifference = $datamin.x - first.x;
					Ydifference = $datamin.y - first.y;
				}
				
				if(Math.abs(Xdifference) > Math.abs(Ydifference) && Math.abs(Xdifference) >= gridSize){
					var insertNum =Math.abs(Xdifference)/gridSize;
					var xInsertVal = Xdifference==0?0:(Xdifference/Math.abs(Xdifference)*gridSize);
					var yInsertVal = Ydifference==0?0:(Ydifference/Math.abs(Ydifference)*gridSize*(Math.abs(Ydifference)/Math.abs(Xdifference)));
					first.isX=true;
				}else if(Math.abs(Xdifference) <= Math.abs(Ydifference) && Math.abs(Ydifference) >= gridSize){
					var insertNum =Math.abs(Ydifference)/gridSize;
					var yInsertVal = Ydifference==0?0:Ydifference/Math.abs(Ydifference)*gridSize;
					var xInsertVal = Xdifference==0?0:(Xdifference/Math.abs(Xdifference)*gridSize*(Math.abs(Xdifference)/Math.abs(Ydifference)));
					first.isX=false;
					//yInsertVal-=(gridPixel/2);
				}else{
					var insertNum = 0;
				}
				
				var dataArr = Object.assign({}, first);
				var x=first.x,y=first.y;
				for(var i=0;i<insertNum;i++){
					var dataArr = Object.assign({}, dataArr);
					x+=xInsertVal;
					y+=yInsertVal;
					
					dataArr.x=Math.ceil(x)>>1<<1;
					dataArr.y=Math.ceil(y)>>1<<1;
					endData.push(dataArr);
				}
			}
			return endData;
		}
		
	}
	
    var tanpucarLoop = function(){
    	for(var k in tanpucarJosn){
    		var carK =tanpucarJosn[k];
    		for(var i in carK){
    			var tempData = carK[i];
    			var rectColor = "#B3B3B3";
				canvasvg.fillStyle(rectColor).fillRect(tempData.x,tempData.y,tempData.w,tempData.h);
    		}
    	}
    	roadAssist(obtainGridList);
    }
	
    var $darwcanvas_ = function(tempData){
		var rectColor = trackNumberColor[tempData.num];
		if(tempData.num < $colorLength){
			rectColor = trackNumberColor[tempData.num];
		}else{
			rectColor = trackNumberColor[$colorLength-1];
		}
		canvasvg.clearRect(tempData.x,tempData.y,tempData.w,tempData.h).fillStyle(rectColor).fillRect(tempData.x,tempData.y,tempData.w,tempData.h);
    }
    
    var updateReport = function(data){
    	var option={
				id:$("#gridID").val(),
				isReport:data,
    	   };
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
//    			isReport = data;
    		}
    	}).post(BASEPATH + '/dcs/asphalt/trace/updateTraceAsphalt.htm', option);
    }
    
    var saveReport = function(less,more,normal,total){
    	var paramJson = [];
    	for(var i in less){
    		if(i=="02"){
    			var rollerType = "胶轮压路机";
    		}else{
    			var rollerType = "钢轮压路机";
    		}
    		
    		paramJson.push({
	    		"time" : $("#gridTime").val(),                                                                // 上传时间
	    		"rollerType" : rollerType,                                                                    // 压路机类型
	    		"lessTargetPass" : less[i] || 0,                                                              // 小于目标遍数
	    		"lessTargetPercent" : less[i] || 0 ? (less[i] / total[i] * 100).toFixed(2) : 0,               // 小于目标遍数百分比
	    		"equalTargetPass" : normal[i] || 0,                                                           // 目标遍数
	    		"equalTargetPercent" :normal[i] || 0 ? (normal[i] / total[i] * 100).toFixed(2) : 0,           // 目标遍数百分比
			    "greaterTargetPass" : more[i] || 0,                                                           // 大于目标遍数
			    "greaterTargetPercent" :more[i] || 0 ? (more[i] / total[i] * 100).toFixed(2) : 0,             // 大于目标遍数百分比
			    "underRate" : less[i] || 0 ? (less[i] / total[i]  * 100).toFixed(2) : 0,                      // 欠压率
			    "overRate"  : more[i] || 0 ? (more[i] / total[i]  * 100).toFixed(2) : 0,                      // 欠压率
	    	});
    	}
    	var option={
			time:$("#gridTime").val(),
			sectionId:sectionId,
        };
    	if(isReport) option.reportId = isReport;
    	option.paramJson = JSON.stringify(paramJson);
    	
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			updateReport(data);
    			$.messager.show({title:'系统提示',msg:"报表生成成功！",timeout:5000,showType:'slide'});
    		}
    	}).post(BASEPATH + '/dcs/report/saveStatisticsReport.htm', option);
    };
    
    var applyReport = function(list){
    	var option={
			time:$("#gridTime").val(),
			sectionId:sectionId,
    	};
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			statisticalTimes;
    			var less = {};
    			var more = {};
    			var normal = {};
    			var total = {};
    			for(var i in list){
    				for(var k in list[i]){
    					if(Number(k)<data.lessTargetPass){
    						if(less[i]){
    							less[i] = less[i] + list[i][k]; 
    						}else{
    							less[i] = list[i][k];
    						}
    					}else if(Number(k)>data.greaterTargetPass){
    						if(more[i]){
    							more[i] = more[i] + list[i][k];
    						}else{
    							more[i] = list[i][k];
    						}
    					}else{
    						if(normal[i]){
    							normal[i] = normal[i] + list[i][k];
    						}else{
    							normal[i] = list[i][k];
    						}
    					}
    					if(total[i]){
    						total[i] = total[i] + list[i][k];
    					}else{
    						total[i] = list[i][k];
    					}
    					
    				}
    			}
    			saveReport(less,more,normal,total);
    		}
    	}).post(BASEPATH + '/roller/statistics/queryRollerNumber.htm', option);
    }
    
    
    var selectAllLoop = function(uid){
    	statisticalTimes["02"] = {};
    	statisticalTimes["03"] = {};
    	var twos = statisticalTimes["02"];
    	var threes = statisticalTimes["03"];
    	for(var k in dataJson){
    		var idarr =dataJson[k];
    		for(var i in idarr){
    			var tempData = idarr[i];
    			var tempThree = tempData["03"];
    			var tempTwo= tempData["02"];
    			if(tempThree){
    				if(!threes[tempThree]){
    					threes[tempThree] = tempThree;
    				}else{
    					threes[tempThree] = threes[tempThree] + tempThree;
    				}
    			}
    			if(tempTwo){
    				if(!twos[tempTwo]){
    					twos[tempTwo] = tempTwo;
    				}else{
    					twos[tempTwo] = twos[tempTwo] + tempTwo;
    				}
    			}
    			if(uid){
    				tempData.num = 0;
					for(var n=0;n<uid.length;n++){
						if(tempData[uid[n]])
						tempData.num += tempData[uid[n]];
					}
				}
    			if(tempData.num != 0) $darwcanvas_(tempData);
    		}
    	}
    	roadAssist(obtainGridList); //重绘路桩
    	if(isReportFlag){
    		applyReport(statisticalTimes);
    		isReportFlag = false;
    	} 
    } 
    
	/**
     *  车辆运行轨迹
     * 第一参数屏幕x坐标，第二参数屏幕y点坐标，第三参数当前温度/当前速度，第四参数判断是遍数，是温度，是速度
     */
	
	var darwRect = function(gX,gY,id,$type){
		var tmpdata = dataJson[gX];
		if(tmpdata){
			tmpdata = tmpdata[gY];
			if(tmpdata){
				var lineID = tmpdata;
				if(lineID[id]){
					lineID[id]=lineID[id]+1;
				}else{
					lineID[id]=1;
				}
				if(lineID[$type]){
					lineID[$type] = lineID[$type] +1;
				}else{
					lineID[$type] = 1;
				}
				lineID.num = lineID.num+1;
			}else{
				var grid={num:1,x:gX,y:gY,w:gridSize,h:gridSize};
				grid[id] = 1;
				grid[$type] = 1;
				dataJson[gX][gY]=grid;
			}
		}else{
			dataJson[gX]={};
			var grid={num:1,x:gX,y:gY,w:gridSize,h:gridSize};
			grid[id] = 1;
			grid[$type] = 1;
			dataJson[gX][gY]=grid;
		}
	}
	
	var tanpucardarwRect = function(gX,gY,id){
		var tmpdata = tanpucarJosn[gX];
		if(tmpdata){
			tmpdata = tmpdata[gY];
			if(!tmpdata){
				var grid={x:gX,y:gY,w:gridSize,h:gridSize};
				tanpucarJosn[gX][gY]=grid;
			}
		}else{
			tanpucarJosn[gX]={};
			var grid={x:gX,y:gY,w:gridSize,h:gridSize};
			tanpucarJosn[gX][gY]=grid;
		}
	}
	
	/**
     * 实时轨迹
     * 
     */
	
	var darwGridLine = function(data){
		$(".errorTip").text("轨迹绘画中");
		if(Object.keys(data).length!=0){
			var trackSelect = $(".trackPlayback li.select").length;
			for(var i in data){
				var darwID = i;
				var darwRes =$("#"+darwID).attr("res");
				var dataList = dataPreprocess(data[i]);
				if(dataList!=0){
					gridPixel = carPicType(darwID,dataList[dataList.length-1]);
//					var carFound = $("#car"+darwID).find("img");
					gridNumber = gridPixel / gridSize;
					for(var i=0;i<dataList.length;i++){
						var resData = dataList[i];
						if(resData.isX){
							var mouseGrid = resData.y - gridPixel /2;
							if(mouseGrid % 2 !=0){
								mouseGrid= mouseGrid+1;
							}
							for(var k=0;k<gridNumber;k++){
								var gX = resData.x; 
								var gY = mouseGrid + gridSize*k; 
								if(darwRes=="01"){
									tanpucardarwRect(gX,gY,darwID);
								}else{
									darwRect(gX,gY,darwID,darwRes);
								}
							}
							/*carFound.css({
								"transform":"rotate(0deg)",
								"marginTop":"0px"
							});*/
						}else{
							var mouseGrid = resData.x - gridPixel /2;
							if(mouseGrid % 2 !=0){
								mouseGrid= mouseGrid+1;
							}
							for(var k=0;k<gridNumber;k++){
								var gX = mouseGrid + gridSize*k;
								var gY =  resData.y;
								if(darwRes=="01"){
									tanpucardarwRect(gX,gY,darwID);
								}else{
									darwRect(gX,gY,darwID,darwRes);
								}
							}
							/*carFound.css({
								"transform":"rotate(270deg)",
								"marginTop":"20px"
							});*/
						}
					}
				}
			}
			tanpucarLoop();
			selectAllLoop();
		}
		scrollFlag = true;
		$(".drawloading").hide();
	}
	
	/**
     *  获取所有轨迹的经纬度
     * 
     */
	
	var dynamictrack = function(){
		var option={
    			time:$("#gridTime").val(),
    			sectionId:sectionId,
    	};
    	ajax.init().success(function(code,msg,data){
    		if(code==0 && data.construction.length!=0){
    			for(var m in data.construction){
    				for(var k in vehicleIdSimplify){
    					if(m==k){
    						$("#"+vehicleIdSimplify[k]).show();
    					}
    				}
    			}
    			locusgridLngLat = data;
    			gridcanvas(data);
    		}
    	}).post(BASEPATH + '/dcs/paverConstructionAction/queryPaverConstruction.htm', option);
	}
	
	
	/**
     *  放大缩小
     * 
     */
	
	var scrollFunc = function (e,data) {
		if(scrollFlag){
			scrollFlag = false;
			e = e || window.event;  
			if (e.wheelDelta || e.type=="click") {  //判断浏览器IE，谷歌滑轮事件          
	        	$(document).off("onmousewheel DOMMouseScroll");
	        	if (e.wheelDelta > 0 || data=="up") { //当滑轮向上滚动时  
	        		if(metre==3){
	                	scrollFlag = true;
	                	return;
	                }else if(metre==300){
	                	metre=10;
	                }else if(metre==10){
	                	metre=3;
	                }
	            }  
	        	if (e.wheelDelta < 0 || data=="down") { //当滑轮向下滚动时  
	            	if(metre==300){
	            		scrollFlag = true;
	            		return;
	            	}else if(metre==3){
	            		metre=10;
	            	}else if(metre==10){
	            		metre=300;
	            	}
	            }
	        	
	            $(".amap-scale-text").text(metre+"米");
	            pixel = metre/60;
	            scaleX =undefined;
	        	scaleY =undefined;
	        	 pageWidth = 0; 
	        	pageHeight = 0;
	        	xOffset = 0;
	        	yOffset = 0;
	            cornersLngLat = [];
	            obtainGridList = [];
	            lngLatGridList=[];
	            dataJson ={};
	            tanpucarJosn = {};
	            endData =[];
	            $("#canvas_").remove();
	            $("#canvas_svg").remove();
	            $(".tanpucar").remove();
	            $(".drawloading").show();
	            lngLatCount(darwCenterPointLngLat);
	            
	        } else if (e.detail) {  //Firefox滑轮事件  
	            if (e.detail> 0) { //当滑轮向下滚动时  
	               alert('下滚')
	            }  
	            if (e.detail< 0) { //当滑轮向上滚动时  
	                alert('上滚')  
	            }  
	        }
		}
    } 
	
	if(navigator.userAgent.indexOf("Firefox")>0){
		if(document.addEventListener){
			document.addEventListener('DOMMouseScroll',scrollFunc,false);
		}
	}else{
		document.onmousewheel = scrollFunc;
	}
    
	 /**
     *  车辆列表绘制
     * 
     */
	
	var vehicleListDraw = function(data){
		$(".trackPlayback ul").html("");
		$(".trackPlayback ul").prepend("<div class='selectAll'><i class='selectCheckbox'></i>全选</div>");
		for(var k in data){
			$("<li id="+data[k].id+" style='display:none' res="+data[k].vehicleType+" rad="+data[k].vehicleWidth+" class ='select track"+data[k].vehicleType+"'><i class='selectCheckbox'></i>"+data[k].vehicleName+"</li>")
			.appendTo($(".trackPlayback ul")).unbind("click").on("click",function(){
				if($(this).children("i").hasClass("checkbox")){
					$(this).addClass("select");
					$(this).children("i").removeClass("checkbox").addClass("selectCheckbox");
					$("#car"+$(this).attr("id")).show();
				}else{
					$(this).removeClass("select");
					$(this).children("i").removeClass("selectCheckbox").addClass("checkbox");
					$("#car"+$(this).attr("id")).hide();
				}
				
				if($(".trackPlayback li.select").length == $(".trackPlayback li").length){
					$(".selectAll").children("i").removeClass("checkbox").addClass("selectCheckbox");
				}else{
					$(".selectAll").children("i").removeClass("selectCheckbox").addClass("checkbox");
				}
				canvasvg.clearRect(0,0,$("#canvas_svg").width(),$("#canvas_svg").height()); //清除所有压路机的轨迹
				var $id = [];
			    var $tanpucar = 0;
				$(".trackPlayback li.select").each(function(){
					if($(this).attr("res")=="01") $tanpucar = 1;
					$id.push($(this).attr("id"));
				});
				
				if($id.length==1 && $tanpucar==1){
					tanpucarLoop();
				}else{
					if($tanpucar==1) tanpucarLoop();
					selectAllLoop($id);
				}
			});
		};
		
		//点击全选
		$(".selectAll").unbind('click').click(function(){
			canvasvg.clearRect(0,0,$("#canvas_svg").width(),$("#canvas_svg").height()); //清除所有压路机的轨迹
			if($(this).children("i").hasClass("checkbox")){
				$(this).children("i").addClass("selectCheckbox").removeClass("checkbox");
				$(this).siblings("li").addClass("select");
				$(this).siblings("li").children("i").addClass("selectCheckbox").removeClass("checkbox");
				$(".vehicle .tanpucar").show();
				var $id = [];
				$(".trackPlayback li.select").each(function(){
					$id.push($(this).attr("id"));
				});
				tanpucarLoop();  //  绘制摊铺车的轨迹
				selectAllLoop($id);  //  绘制全部压路机的的轨迹
			}else{
				$(this).children("i").addClass("checkbox").removeClass("selectCheckbox");
				$(this).siblings("li").removeClass("select");
				$(this).siblings("li").children("i").addClass("checkbox").removeClass("selectCheckbox");
				$(".vehicle .tanpucar").hide();
				roadAssist(obtainGridList); //重绘路桩
			}
		});
	}
	
    /**
     *  get车辆列表
     * 
     */
	
    var vehicleList = function(){
    	var option = {
    			time:$("#gridTime").val(),
    			sectionId:sectionId
    		}
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			for(var k in data){
    				if(!vehicleIdSimplify[data[k].id]){
    					vehicleIdSimplify[data[k].id]="00"+k;
    				}
    				data[k].id = "00"+k;
    			}
    			vehicleAllList = data;
    			vehicleListDraw(data);
    		}
    	}).post(BASEPATH + '/dcs/intface/querySysConstructionVehicleByAreaId.htm', option);
    } 
	
	//鼠标点击放大按钮
	$("#zoom_enlarge").click(function(){
		scrollFunc(null,"up");
	});
	
	//鼠标点击缩小按钮
	$("#zoom_reduce").click(function(){
		scrollFunc(null,"down");
	});
    
    exports.trans = function(){
    	$(".drawloading").show();
    	getCenterPoint();
	}
});

